export default {
	namespaced: true,
	state: {
		// 购物车中的商品列表数据
		cartGoodsList: uni.getStorageSync('cartGoodsList') || []
	},
	mutations: {
		// 加入购物车
		addCart(state, goods) {
			const resulut = state.cartGoodsList.find(item => item.goods_id === goods.goods_id)
			if (!resulut) {
				state.cartGoodsList.push(goods)
			} else {
				resulut.goods_number++
			}
			// 将购物车商品列表数据存入本地
			uni.setStorageSync('cartGoodsList', state.cartGoodsList)
		},
		// 修改商品的选中状态
		changeState(state, index) {
			// 找到当前点击的商品
			state.cartGoodsList[index].goods_state = !state.cartGoodsList[index].goods_state
			// 将购物车商品列表数据存入本地
			uni.setStorageSync('cartGoodsList', state.cartGoodsList)
		},
		// 修改全选的选中状态
		changeAllState(state, isAllSelected) {
			state.cartGoodsList.forEach(item => item.goods_state = isAllSelected)
			// 将购物车商品列表数据存入本地
			uni.setStorageSync('cartGoodsList', state.cartGoodsList)
		},
		// 修改商品数量
		changeNumber(state, {
			index,
			num
		}) {
			if (state.cartGoodsList[index].goods_number < 2 && num === -1) return
			state.cartGoodsList[index].goods_number += num
			// 将购物车商品列表数据存入本地
			uni.setStorageSync('cartGoodsList', state.cartGoodsList)
		}
	},
	getters: {
		// 计算全选的选中状态
		isAllSelected(state) {
			return state.cartGoodsList.every(item => item.goods_state)
		},
		// 计算商品总数量
		totalNum(state) {
			// let total = 0
			// state.cartGoodsList.forEach(item => {
			// 	if (item.goods_state) {
			// 		total += item.goods_number
			// 	}
			// })
			// return total
			return state.cartGoodsList.reduce((prev, cur) => {
				if (cur.goods_state) {
					prev += cur.goods_number
				}
				return prev
			}, 0)
		}
	}
}
